import React, { useState, forwardRef, useImperativeHandle } from 'react';

function Counter(props, ref) {
  // 把ref对象的改变动作放到useState()之前，不会触发组件重新渲染。
  useImperativeHandle(ref, () => ({
    getFromData: () => {
      return formValue
    }
  }))
  const [formValue, setFormValue] = useState({ name: 'ky', age: 18 })
  const setVal = (e, keyName) => {
    let obj = Object.assign({}, formValue, {
      [keyName]: e.target.value
    })
    setFormValue(obj)
  }
  return (<div>
    <h2>{props.data} </h2>
    <h2>姓名：<input type="text" value={formValue.name} onChange={(e) => { setVal(e,'name') }} /> </h2>
    <h2>年龄：<input type="text" value={formValue.age} onChange={(e) => { setVal(e, 'age') }}/> </h2>
  </div>)
}
Counter = forwardRef(Counter)

export default Counter;